<template>
  <div class="watch-demo">
    <h2>👁️ 智能监控系统</h2>
    
    <div class="demo-section">
      <h3>📊 watch 定点监控</h3>
      <div class="monitor-panel">
        <div class="input-group">
          <label>用户ID监控：</label>
          <input 
            v-model.number="userId" 
            type="number" 
            min="1" 
            max="10"
            placeholder="输入1-10的用户ID"
          >
          <span class="input-tip">当前ID: {{ userId }}</span>
        </div>
        
        <div class="monitor-display">
          <div class="monitor-item">
            <span class="label">监控状态：</span>
            <span :class="['status', monitoringStatus]">{{ monitoringStatusText }}</span>
          </div>
          <div class="monitor-item">
            <span class="label">用户数据：</span>
            <span class="data">{{ userData || '暂无数据' }}</span>
          </div>
          <div class="monitor-item">
            <span class="label">变更记录：</span>
            <div class="change-log">
              <div v-for="(log, index) in changeLogs" :key="index" class="log-item">
                {{ log }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="demo-section">
      <h3>🚁 watchEffect AI巡检</h3>
      <div class="tracking-panel">
        <div class="coordinates">
          <div class="coord-item">
            <span class="coord-label">X坐标：</span>
            <input v-model.number="x" type="range" min="0" max="100" class="coord-slider">
            <span class="coord-value">{{ x }}</span>
          </div>
          <div class="coord-item">
            <span class="coord-label">Y坐标：</span>
            <input v-model.number="y" type="range" min="0" max="100" class="coord-slider">
            <span class="coord-value">{{ y }}</span>
          </div>
        </div>
        
        <div class="tracking-area">
          <div class="area-title">巡检区域 ({{ x }}, {{ y }})</div>
          <div class="tracking-grid">
            <div 
              class="tracking-point" 
              :style="{ left: x + '%', top: y + '%' }"
            ></div>
          </div>
        </div>
        
        <div class="tracking-logs">
          <h4>📝 巡检日志</h4>
          <div class="log-container">
            <div v-for="(log, index) in trackingLogs" :key="index" class="tracking-log-item">
              <span class="log-time">{{ log.time }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="demo-section">
      <h3>🎯 综合监控面板</h3>
      <div class="control-panel">
        <button @click="startMonitoring" :disabled="isMonitoring" class="control-btn start">
          🟢 开始监控
        </button>
        <button @click="stopMonitoring" :disabled="!isMonitoring" class="control-btn stop">
          🔴 停止监控
        </button>
        <button @click="clearLogs" class="control-btn clear">
          🧹 清空日志
        </button>
      </div>
      
      <div class="system-status">
        <div class="status-item">
          <span class="status-label">系统状态：</span>
          <span :class="['system-status-indicator', systemStatus]">{{ systemStatusText }}</span>
        </div>
        <div class="status-item">
          <span class="status-label">监控模式：</span>
          <span class="monitor-mode">{{ monitoringMode }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, watchEffect } from 'vue'

// 用户ID监控相关
const userId = ref<number>(1)
const userData = ref<string>('')
const monitoringStatus = ref<string>('idle')
const changeLogs = ref<string[]>([])

// 坐标追踪相关
const x = ref<number>(50)
const y = ref<number>(50)
const trackingLogs = ref<Array<{time: string, message: string}>>([])

// 系统状态
const isMonitoring = ref<boolean>(false)
const systemStatus = ref<string>('ready')

// 模拟用户数据
const mockUserData = {
  1: '张三 - 管理员',
  2: '李四 - 编辑',
  3: '王五 - 用户',
  4: '赵六 - VIP用户',
  5: '钱七 - 普通用户',
  6: '孙八 - 高级用户',
  7: '周九 - 管理员',
  8: '吴十 - 编辑',
  9: '郑十一 - 用户',
  10: '王十二 - VIP用户'
}

// 计算属性 - 监控状态文本
const monitoringStatusText = computed(() => {
  const statusMap = {
    idle: '待机中',
    watching: '监控中',
    loading: '加载中',
    error: '错误'
  }
  return statusMap[monitoringStatus.value] || '未知状态'
})

// 计算属性 - 系统状态文本
const systemStatusText = computed(() => {
  const statusMap = {
    ready: '准备就绪',
    running: '运行中',
    paused: '已暂停',
    stopped: '已停止'
  }
  return statusMap[systemStatus.value] || '未知状态'
})

// 计算属性 - 监控模式
const monitoringMode = computed(() => {
  return isMonitoring.value ? '自动巡检' : '手动监控'
})

// watch - 监听用户ID变化（定点监控）
watch(userId, async (newId, oldId) => {
  console.log(`👁️ watch检测到用户ID变化: ${oldId} → ${newId}`)
  
  // 记录变更日志
  const timestamp = new Date().toLocaleTimeString()
  changeLogs.value.unshift(`[${timestamp}] 用户ID: ${oldId} → ${newId}`)
  
  // 限制日志数量
  if (changeLogs.value.length > 5) {
    changeLogs.value = changeLogs.value.slice(0, 5)
  }
  
  // 模拟数据加载
  monitoringStatus.value = 'loading'
  userData.value = ''
  
  try {
    // 模拟异步数据获取
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const data = mockUserData[newId as keyof typeof mockUserData] || '未知用户'
    userData.value = data
    monitoringStatus.value = 'watching'
    
    console.log(`✅ 成功获取用户数据: ${data}`)
  } catch (error) {
    monitoringStatus.value = 'error'
    userData.value = '获取数据失败'
    console.error('❌ 获取用户数据失败:', error)
  }
}, { 
  immediate: true // 立即执行一次
})

// watchEffect - 自动追踪坐标变化（AI巡检）
const stopTracking = watchEffect(() => {
  // 这个函数会自动追踪x和y的变化
  const timestamp = new Date().toLocaleTimeString()
  const message = `坐标变化: (${x.value}, ${y.value})`
  
  console.log(`🚁 watchEffect巡检: ${message}`)
  
  // 添加到追踪日志
  trackingLogs.value.unshift({
    time: timestamp,
    message: message
  })
  
  // 限制日志数量
  if (trackingLogs.value.length > 8) {
    trackingLogs.value = trackingLogs.value.slice(0, 8)
  }
  
  // 模拟智能分析
  if (x.value > 80 || y.value > 80) {
    console.log('⚠️ 检测到异常坐标值！')
  }
})

// 开始监控
const startMonitoring = () => {
  isMonitoring.value = true
  systemStatus.value = 'running'
  monitoringStatus.value = 'watching'
  console.log('🟢 监控系统已启动')
}

// 停止监控
const stopMonitoring = () => {
  isMonitoring.value = false
  systemStatus.value = 'stopped'
  monitoringStatus.value = 'idle'
  console.log('🔴 监控系统已停止')
}

// 清空日志
const clearLogs = () => {
  changeLogs.value = []
  trackingLogs.value = []
  console.log('🧹 日志已清空')
}

// 清理函数（组件卸载时停止追踪）
onUnmounted(() => {
  stopTracking()
})
</script>

<style scoped>
.watch-demo {
  max-width: 900px;
  margin: 30px auto;
  padding: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  color: white;
  font-family: 'Arial', sans-serif;
}

.watch-demo h2 {
  text-align: center;
  margin-bottom: 30px;
  font-size: 28px;
}

.demo-section {
  background: rgba(255, 255, 255, 0.1);
  padding: 25px;
  border-radius: 15px;
  margin-bottom: 25px;
}

.demo-section h3 {
  margin-bottom: 20px;
  font-size: 20px;
  color: #42b883;
}

.monitor-panel, .tracking-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 15px;
}

.input-group label {
  font-weight: bold;
  min-width: 100px;
}

.input-group input {
  padding: 8px 12px;
  border: none;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  font-size: 14px;
}

.input-tip {
  font-size: 12px;
  opacity: 0.8;
}

.monitor-display {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.monitor-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
}

.label {
  font-weight: bold;
  min-width: 80px;
  color: #42b883;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status.idle {
  background: rgba(255, 193, 7, 0.2);
  color: #ffc107;
}

.status.watching {
  background: rgba(40, 167, 69, 0.2);
  color: #28a745;
}

.status.loading {
  background: rgba(23, 162, 184, 0.2);
  color: #17a2b8;
}

.status.error {
  background: rgba(220, 53, 69, 0.2);
  color: #dc3545;
}

.data {
  background: rgba(255, 255, 255, 0.1);
  padding: 6px 10px;
  border-radius: 4px;
  font-size: 14px;
}

.change-log {
  display: flex;
  flex-direction: column;
  gap: 5px;
  max-height: 100px;
  overflow-y: auto;
}

.log-item {
  background: rgba(255, 255, 255, 0.05);
  padding: 5px 8px;
  border-radius: 3px;
  font-size: 12px;
  font-family: 'Courier New', monospace;
}

.coordinates {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.coord-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.coord-label {
  font-weight: bold;
  min-width: 60px;
  color: #42b883;
}

.coord-slider {
  flex: 1;
  height: 6px;
  border-radius: 3px;
  background: rgba(255, 255, 255, 0.3);
  outline: none;
  -webkit-appearance: none;
}

.coord-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #42b883;
  cursor: pointer;
}

.coord-value {
  font-weight: bold;
  min-width: 30px;
  text-align: center;
  background: rgba(255, 255, 255, 0.1);
  padding: 4px 8px;
  border-radius: 4px;
}

.tracking-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.area-title {
  font-size: 14px;
  opacity: 0.8;
}

.tracking-grid {
  position: relative;
  width: 200px;
  height: 200px;
  background: rgba(255, 255, 255, 0.1);
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 10px;
}

.tracking-point {
  position: absolute;
  width: 12px;
  height: 12px;
  background: #ff6b6b;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.3s ease;
  box-shadow: 0 0 10px rgba(255, 107, 107, 0.5);
}

.tracking-logs h4 {
  margin-bottom: 10px;
  color: #42b883;
}

.log-container {
  display: flex;
  flex-direction: column;
  gap: 5px;
  max-height: 120px;
  overflow-y: auto;
  background: rgba(0, 0, 0, 0.2);
  padding: 10px;
  border-radius: 5px;
}

.tracking-log-item {
  display: flex;
  gap: 10px;
  font-size: 12px;
  font-family: 'Courier New', monospace;
}

.log-time {
  color: #42b883;
  min-width: 60px;
}

.log-message {
  color: #ffffff;
}

.control-panel {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-bottom: 20px;
}

.control-btn {
  padding: 10px 20px;
  font-size: 14px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: bold;
}

.control-btn.start {
  background: #28a745;
  color: white;
}

.control-btn.stop {
  background: #dc3545;
  color: white;
}

.control-btn.clear {
  background: #6c757d;
  color: white;
}

.control-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.system-status {
  display: flex;
  justify-content: space-around;
  background: rgba(0, 0, 0, 0.2);
  padding: 15px;
  border-radius: 10px;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.status-label {
  font-size: 12px;
  opacity: 0.8;
}

.system-status-indicator {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: bold;
}

.system-status-indicator.ready {
  background: rgba(255, 193, 7, 0.2);
  color: #ffc107;
}

.system-status-indicator.running {
  background: rgba(40, 167, 69, 0.2);
  color: #28a745;
}

.system-status-indicator.paused {
  background: rgba(23, 162, 184, 0.2);
  color: #17a2b8;
}

.system-status-indicator.stopped {
  background: rgba(108, 117, 125, 0.2);
  color: #6c757d;
}

.monitor-mode {
  background: rgba(255, 255, 255, 0.1);
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: bold;
  color: #42b883;
}
</style>